<template>
    <component
            v-show="visible"
            v-if="currentComponent"
            :is="currentComponent"
            :name="name"
            :ext="ext"
            :src="src"
            :id="id"
            @exit="onExit"
    ></component>
</template>

<script>
    import {ENABLE_FILE_PREVIEW_SERVER} from "~/Contants";

    const previewComponents = [
        {
            ext:["pdf"],
            component:()=>import("~/components/file-list/preview-components/PdfScrollPreviewer"),
        },
        {
            ext:["BMP","JPG","JPEG","PNG","GIF","ICO","GIF"],
            component: ()=>import("~/components/file-list/preview-components/ImagePreviewer"),
        },
        {
            ext:[".*"],
            component: ()=>import("~/components/file-list/preview-components/CommonFilePreviewer"),
            disable: !ENABLE_FILE_PREVIEW_SERVER,
        },
    ];
    export default {
        name: "Previewer",
        props:{
            visible:{
                type:Boolean,
                default: true
            },
        },
        data(){
            return{
                previewComponents,
                currentComponent:null,
                name:"",
                ext:"",
                src:"",
                id: -1,
            }
        },
        mounted() {
            this.$on("reload",this.loadFile);
        },
        methods:{
            onExit(message,title,type){
                this.$emit("update:visible",false);
                this.$emit("exit");
                this.currentComponent = null;
                if(message){
                    title = title || '无法预览';
                    type = type || 'error';
                    this.$alert(message,title,{type:type});
                }
            },
            loadFile(name,ext,src,id){
                if(!src||src.length===0)return undefined;
                const componentMeta = this.previewComponents.find(v=>{
                    if(!v.ext || v.disable === true)return false;
                    return v.ext.some(e=>new RegExp(e,"i").test(ext))
                });
                if(!componentMeta){
                    this.$emit("unsupported");
                    return undefined;
                }
                this.src = src;
                this.name = name;
                this.ext = ext;
                this.id = id;
                this.$emit("loading");
                this.currentComponent = componentMeta.component;
            }
        }
    }
</script>

<style scoped>

</style>
